var RNFS = require('react-native-fs');
import RNFileSelector from 'react-native-file-selector';
import React, { Component } from 'react';
import FileUtil from '../../../../utils/file'
import { Videos, videopath, userpath, examinationpath, gradepath } from '../../../../utils/path'

import { headers, data } from '../json'
import XLSX from 'xlsx';
import { Modal, View, Text, TextInput, TouchableHighlight, StyleSheet, Image, ImageBackground, TouchableOpacity, PermissionsAndroid, Alert, Pressable,Dimensions,ToastAndroid } from 'react-native'
import { color } from 'react-native-reanimated';
import { changeloginStatus, getexam } from '../../../../actions/actionCreators'
import store from '../../../../store/configureStore'
import { RadioGroup, RadioButton } from 'react-native-flexi-radio-button'
import  RNPop from './model'

const win_width = Dimensions.get('window').width;
const win_height = Dimensions.get('window').height;
class SaveTikumodel extends Component {
    constructor(props) {
        super(props);
        this.myRef = React.createRef();
        this.state = {
            ...store.getState(),
            title: "",//答题标题，
            sort: "",//答题顺序,
            count: "",
            examname: "",
            path: "选择文件",
            danxuan: "",
            duoxuan: "",
            panduan: "",
            Allcount: "",
            picturepath: "",
            fmModalVisible: false,
            maketestVisible: false,
            images: [],
            imgindex: "",
            currentitem: "",
            checkarr: []
        }
        //   是一个子组件，当homepage刷新就开始执行这一步，虽然这个弹窗还没有开启，只执行一次,但是render只要开启就会执行取到
        console.log(store.getState().getexams, props)
        store.subscribe(this._storeChange)//这一步必不可少，否则可能导致异步操作在这个生命周期store.getState().getexams取到的值为空，后面异步操作完成需要这边监听再更新,而且这边更新state那边store也会同步更新。为什么props为空，因为弹框没开启没点击事件examitem: "", examindex: ""为空，而这个子组件的生命周期跟着父组件只执行最开始渲染的第一次，但是这个props在弹框开启的时候虽然这个生命周期不执行了但是在别的地方能取到props

    }


    _storeChange = () => {
        // 实现redux和组件同步更新
        /**
         * 当我感知到数据发生变化的时候，我去调用store.getState()从store里面重新去取数据
         * 然后调用setState替换掉当前组件里面的数据
         */
        this.setState(store.getState())
    }
    /*读取文件*/
    getfile = () => {
        RNFileSelector.Show(
            // 外部存储卡的数据内容复制到安卓内置内存的某个文件夹
            {
                // path:'/data/user/0/com.awesomeproject/',//可以自定义路径
                path: '/storage/',//可以自定义路径
                title: '请选择文件',
                onDone: async (path) => {
                    RNFS.readFile(path, 'ascii').then(res => {
                        const workbook = XLSX.read(res, { type: 'binary' });
                        console.log(workbook)
                        // 读取到保存的excel新文件进行修改字段操作
                        var worksheet = workbook.Sheets[workbook.SheetNames[0]];
                        var jsondata = XLSX.utils.sheet_to_json(worksheet);
                        const sliceArr = jsondata.slice(3)
                        let danxuan = 0
                        let duoxuan = 0
                        let panduan = 0
                        sliceArr.map(item => {
                            // 每个数据都会执行下面代码 || !item['score_'] 
                            if (!item['answer'] || !item['content'] || !item['content_1'] || !item['content_2'] || !item['order'] || !item['topic_type']) {
                                // 如果·有一个为空，后面不执行，提示答题表信息不完整，请参照模板
                                Alert.alert('提示', '答题表信息不完整，请参照模板', [
                                    {
                                        text: '取消',
                                        onPress: () => console.log('Cancel Pressed'),
                                        style: 'cancel'
                                    },
                                    { text: '确定', onPress: () => console.log('OK Pressed') },
                                ]);
                            } else {
                                // 统计单选题，多选题,文件名，同时把名字作为标题 把path路径存在state
                                var filename = path.substring(path.lastIndexOf('/'))
                                var name = filename.split('.')[0].split('/')[1]
                                this.setState({ path: path, title: name, examname: name })
                                if (item.topic_type == 1) {
                                    danxuan += 1
                                } else if (item.topic_type == 2) {
                                    duoxuan += 1

                                } else if (item.topic_type == 3) {
                                    panduan += 1
                                }
                            }
                        })
                        console.log(sliceArr)
                        console.log(danxuan, duoxuan)
                        this.setState({ danxuan: danxuan, duoxuan: duoxuan, panduan: panduan, Allcount: sliceArr.length })

                    })

                },
                onCancel: () => {
                    console.log('cancelled')
                }
            })

    }

    onChangeText = (text) => {
        // var obj={...this.state.currentitem, title: text}//更新不及时，永远在上一次的记录
        var obj = Object.assign(this.props.examitem, { title: text })
        this.setState({ currentitem: obj, title: text })
        console.log(this.state.currentitem)
    }
    onChangesort = (text) => {
        const newText = text.replace(/[^\d]+/, '');
        this.setState({ sort: newText })
    }
    choosefm = async () => {
        //出题弹窗
        this.setState({ maketestVisible: true })



    }
    _onPressButton(val, item) {
        let path = item ? item.path : ''
        this.setState({ imgindex: val + 1, picturepath: path })
        console.log(val, item)
    }
    onPressFunction = () => {
        // 如果题目《10题，禁止测题,如果没有count值，不让进入
        if (!this.state.count) {
            ToastAndroid.showWithGravity('请选择出题数量', ToastAndroid.SHORT,
            ToastAndroid.CENTER)
            return
        }
        this.props.SavetimucloseVisible(false)
        this.setState({ maketestVisible: false, fmModalVisible: false })
        this.props.entermaketest(this.props.examitem, this.state.count)



    }
    onSelect(index, value) {
        console.log(index, value)
        this.setState({
            count: value
        })
    }
    readexamfile = (value) => {
        // 写入文件
        RNFS.writeFile(examinationpath, JSON.stringify(value), 'utf8')
            .then((success) => {
                console.log('FILE WRITTEN!4444444');
                ToastAndroid.showWithGravity('操作成功', ToastAndroid.SHORT,
                ToastAndroid.CENTER)
                var action = getexam()
                store.dispatch(action)


            })
            .catch((err) => {
                console.log(err.message);
            })


    }
    delgrade = () => {
        RNFS.readFile(gradepath, 'utf8').then(res => {
            var arr = JSON.parse(res)
            // 更新表字段【成绩表id，题库id，题库平均分数，人数】看当前成绩表题库的id在表里存在不存在，不存在说明第一次存，自定义答题人数为1追加数据。存在说明这答题表已经有人答题，在原来的答题人数上面加1，修改记录，平均分数结合当前答题分数重新计算平均分数
            let index1
            var flagvalue = arr.find((item, index) => {
                index1 = index
                return item.examid == this.props.examitem.id
            })
            //结算表存在相关成绩答题卡id的成绩就删除，没有就不操作
            if (flagvalue) {
                arr.splice(index1, 1)
                // console.log(arr, this.props.examitem)

                RNFS.writeFile(gradepath, JSON.stringify(arr), 'utf8')
                    .then((success) => {
                        console.log('FILE WRITTEN333333333!');
                        // Alert.alert('提示', '删除成功', [
                        //     { text: '确定', onPress: () => console.log('OK Pressed') },

                        // ]);
                    })
                    .catch((err) => {
                        console.log(err.message);
                    })
            }
            //   console.log(arr)
        })

    }
    savetitle = () => {
        // 修改标题
        let index1
        var arr = store.getState().getexams

        arr.map((item, index) => {
            if (item.id == this.props.examitem.id) {
                index1 = index
            }
        })
        arr[index1] = this.props.examitem
        console.log(JSON.stringify(arr))//已更新
        //更新下最新数据在写入
        this.readexamfile(arr)



    }
    savesort = () => {
        // 保存顺序
        if (!this.state.sort) {
            // // 没有选中
            // Alert.alert('提示', '请填入目标顺序再操作', [
            //     { text: '确定', onPress: () => console.log('OK Pressed') },

            // ]);
            ToastAndroid.showWithGravity('请填入目标顺序再操作', ToastAndroid.SHORT,
            ToastAndroid.CENTER)
            return false
        }
        console.log(this.state.getexams)//有时获取不到位空数组,导致报错，问题未知

        var arr = store.getState().getexams
        //   如果可改变顺序同一个数据条可以出现在不同的位置。所以不能用固定的this.props.examindex
        // 根据id判断索引
        let index1
        arr.map((item, index) => {
            if (item.id == this.props.examitem.id) {
                index1 = index
            }
        })
        var arr1 = arr.splice(index1, 1)//删除位置是4索引是3的
        arr1.unshift(this.state.sort - 1, 0);//这个存在的意义是把数据放到索引是6位置是7,arr1=[6,0,4] arr=[1,2,3,5,6,7,8]
        Array.prototype.splice.apply(arr, arr1) //等价于arr.splice(6,0,4),arr从索引6开始，删除0个，再加一个参数放在此位置; 
        console.log(arr, arr1)
        this.readexamfile(arr)

        //   var obj= Object.assign(this.props.examitem,{sort: this.state.sort})
        //   this.state.getexams[this.props.examindex-1]=obj
        //  调换数组位置 this.state.sort来改变真实的索引
        //   arr1 = ['a', 'b', 'c'] 
        //   arr2 = ['1', '2', '3'] 
        //如果按照原生写传的参就是一个数组arr2：arr1.splice(2, 0, arr2)=[a,b,[1,2,3],c]
        //利用apply(对象，[参数])=》把参数分散了，
        //arr2.unshift(2, 0); 把删除的位置和删除的个数这样记录着 arr2=[2,0,1,2,3]
        //apply改变this指向，第二个位置是把所有参数用数组包裹，这样就导致传的参不是数组,就变成了一个一个的arr1.splice(2,0,'1','2','3')，而是数组里面的1,2,3。 Array.prototype.splice.apply(arr1, arr2)==
        //arr1.splice(2,0,'1','2','3'); 
    }
    del = () => {
        // 删除题库，删除表里面数据，在删除实际答题表，【是否把该题库id的成绩表相关数据[平均分答题人数之类]也删除】
        // 找到id 删除
        let rnPop = this.refs.rnPop
        rnPop.show({content:"题库删除后该题库所有的得分记录都会删除，如需删除请点击确定",btns:[
            {
                text: '确定',
                style: {color: '#30a4fc'},
                onPress:async () => {
                    let index1
                    this.state.getexams.map((item, index) => {
                        if (item.id == this.props.examitem.id) {
                            index1 = index
                        }
                    })
                    console.log(this.props.examitem.exampath)
                    // 先删除改路径下的excel答题文件
                    await RNFS.unlink(this.props.examitem.exampath)
                        .then(() => {
                            console.log('FILE DELETED');
                            this.delgrade()//删除成绩

                            // 刷新数据
                            this.state.getexams.splice(index1, 1)//在题库数据删除索引是index1的在重新写入
                            console.log(this.state.getexams, store.getState().getexams)
                            this.readexamfile(this.state.getexams)//store也会同步更新列表界面也及时更新，写入新数据列表后不用在重新请求列表

                        })
                        .catch((err) => {
                            console.log(err.message);
                        })

                },
            },
            { text: '取消', onPress: () => console.log('取消') }

            
        ]})
    



    }


    render() {
        console.log(this.props.examitem)
        var count = this.props.examitem.Allcount
        let checkarr;
        if (count >= 50) {
            checkarr = [10, 20, 50]
        } else if (count >= 20) {
            checkarr = [10, 20]
        } else if (count >= 10) {
            checkarr = [10]
        } else {
            // 小于10题不提供答题要求重载题库
            // checkarr=[count]
            checkarr = []

        }
        // this.setState({checkarr:checkarr})
        this.myRef.current = checkarr
        // console.log(this.myRef.current)

        return (
            <Modal
                animationType="slide"
                transparent={true}
                // 继承属性和方法
                visible={this.props.SaveTikumodelVisible}
                onRequestClose={() => {
                    Alert.alert("Modal has been closed.");
                }}
            >
                  <RNPop ref="rnPop" />
                <View style={styles.centeredView}>

                    <ImageBackground style={{ ...styles.modalView }}
                        source={require('../../../../../assets/imgs/a1/background.png')}
                        imageStyle={{ resizeMode: 'stretch' }}

                    >
                        <Text style={styles.modalText}>{this.props.examitem.title}</Text>

                        <Pressable style={{ position: "absolute", right: 15, top: 10,zIndex:100, }} onPress={() => { this.props.SavetimucloseVisible(false) }}><Image
                            style={{ width: 40, height: 40 }}
                            source={require('../../../../../assets/imgs/close.png')}

                        /></Pressable >

                        <View style={styles.contaner}>

                            <View style={styles.contanerleft}>
                                <View>
                                    <TextInput
                                        style={{ height: 40, borderColor: '#62AEDD', backgroundColor: "#3070AF", borderWidth: 1, color: "#fff" }}
                                        onChangeText={text => this.onChangeText(text)}
                                        clearButtonMode='while-editing'
                                        selectionColor="black"
                                        value={this.props.examitem.title}
                                    />
                                </View>
                                <View style={{ justifyContent: 'flex-end', flexDirection: "row", marginTop: 15 }}>
                                    <Text style={{ color: "#fff", lineHeight: 30 }}>选中题库从当前位置 {this.props.examindex} 移动到</Text>
                                    <TextInput
                                        multiline={true}
                                        style={{ height: 35, width: 40, lineHeight: 20, borderBottomColor: '#fff', borderBottomWidth: 1, color: "#D59652" }}
                                        onChangeText={text => this.onChangesort(text)}
                                        clearButtonMode='while-editing'
                                        selectionColor="black"
                                        value={this.state.sort}
                                    />
                                    <Text style={{ color: "#fff", lineHeight: 30 }}>位置</Text>
                                </View>
                                {/* <ImageBackground style={styles.tinyLogo}
                                    source={{ uri: `file://${this.state.picturepath}` }}
                                    >
                                    <View style={styles.tikutitle}>
                                        <Text style={{ textAlign: "center", color: "#fff" }}>{this.state.title || '标题'}</Text>
                                    </View>
                                    <View style={styles.yikutype}>
                                        <Text style={{ color: "#fff", fontSize: 10 }} >单选题:{this.state.danxuan}</Text>
                                        <Text style={{ color: "#fff", fontSize: 10 }} >多选题:{this.state.duoxuan}</Text>
                                        <Text style={{ color: "#fff", fontSize: 10 }} >判断题:{this.state.panduan}</Text>
                                    </View>

                                </ImageBackground> */}



                            </View>
                            <View style={styles.contanerright}>
                                <TouchableHighlight
                                    style={{ ...styles.chooseButton }}
                                // onPress={this.login}
                                >
                                    <Text style={styles.textStyle} onPress={() => { this.savetitle() }}>修改标题</Text>
                                </TouchableHighlight>

                                <TouchableHighlight
                                    style={{ ...styles.chooseButton }}
                                // onPress={this.login}
                                >
                                    <Text style={styles.textStyle} onPress={() => { this.savesort() }}>移动排序</Text>



                                </TouchableHighlight>
                                <TouchableHighlight
                                    style={{ ...styles.chooseButton }}
                                // onPress={this.login}
                                >
                                    <Text style={styles.textStyle} onPress={() => { this.props.handtimucloseVisible(true, this.props.examitem) }}>重载题库</Text>



                                </TouchableHighlight>
                                <TouchableHighlight
                                    style={{ ...styles.chooseButton }}
                                // onPress={this.login}
                                >
                                    <Text style={styles.textStyle} onPress={() => { this.choosefm() }}>出卷</Text>



                                </TouchableHighlight>
                                <Modal
                                    animationType="slide"
                                    transparent={true}
                                    // 继承属性和方法
                                    visible={this.state.maketestVisible}
                                    // presentationStyle='formSheet'
                                    onRequestClose={() => {
                                        Alert.alert("Modal has been closed.");
                                    }}
                                >
                                   <View style={{flex: 1,
        justifyContent: "center",
        alignItems: "center",
        marginTop: 22}}>
                                   <ImageBackground style={{ ...styles.modalView1 }}
                        source={require('../../../../../assets/imgs/a1/background.png')}
                        imageStyle={{ resizeMode: 'stretch' }}

                    >
                                        <Text style={{ color: "#fff" }}>{this.props.examitem.title}</Text>
                                        <Pressable style={{ position: "absolute", right: 15, top: 10,zIndex:100, }} onPress={() => { this.setState({ maketestVisible: false }) }}><Image
                                            style={{ width: 40, height: 40 }}
                                            source={require('../../../../../assets/imgs/close.png')}

                                        /></Pressable >
                                        <View style={styles.choosefengmian}>

                                            <View style={{ flexDirection: "row" }}>
                                                <Text style={{ color: "#fff" }}>试卷标题：</Text>
                                                <View style={{ width: 200, borderWidth: 1, borderColor: '#309ED0', backgroundColor: "#3070AF", padding: 5, top: -5 }}><Text style={{ color: "#fff" }}>{this.props.examitem.title}</Text></View>
                                            </View>

                                            <View style={{ flexDirection: "row", marginTop: 20 }}>
                                                <Text style={{ color: "#fff" }}>出题数量：</Text>



                                                {
                                                    checkarr.length > 0 ? (
                                                        <RadioGroup
                                                            onSelect={(index, value) => this.onSelect(index, value)}
                                                            style={styles.radios}
                                                            color='#fff'
                                                        // selectedIndex={0}
                                                        // highlightColor='#ccc8b9'
                                                        >
                                                            {
                                                                checkarr.map((item, index) => {
                                                                    return (
                                                                        <RadioButton key={index} value={item} color='#fff' activeColor='' highlightColor=''>
                                                                            <Text style={{ color: "#fff" }}>{item}</Text>
                                                                        </RadioButton>
                                                                    )
                                                                })

                                                            }
                                                        </RadioGroup>
                                                    ) : (<Text style={{ color: "#fff" }}>题库数量＜10，请使用重载题库功能，更新题库。</Text>)
                                                }




                                            </View>
                                            <View >
                                                {
                                                    checkarr.length > 0 ? (
                                                        <Pressable onPress={this.onPressFunction} style={{ backgroundColor: "#CC975D", width: 80, justifyContent: "center", alignItems: "center", ...styles.chooseButton, marginTop: 50, }}>
                                                            <Text style={{ color: "#fff", fontSize: 15 }} >生成试卷</Text>
                                                        </Pressable>
                                                    ) : (null)
                                                }

                                            </View>

                                        </View>

                                    </ImageBackground>

                                   </View>
                                </Modal>
                            </View>
                        </View>

                        <TouchableHighlight
                            style={{ ...styles.openButton }}
                        // onPress={this.login}
                        >
                            <Text style={styles.textStyle} onPress={() => { this.del() }}>删除题库</Text>
                        </TouchableHighlight>
                    </ImageBackground>
                </View>
            </Modal>
        );
    }
}

export default SaveTikumodel;
const styles = StyleSheet.create({
    // model样式
    centeredView: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
        marginTop: 22
    },
    modalView: {
        width: 500,
        height: 300,
        margin: 20,
        // backgroundColor: "#3078BB",
        borderRadius: 20,
        padding: 35,
        alignItems: "center",
        shadowColor: "#000",
        shadowOffset: {
            width: 0,
            height: 2
        },
        shadowOpacity: 0.25,
        shadowRadius: 3.84,
        elevation: 5
    },
    modalView1: {
        width: 500,
        height: 300,
        backgroundColor: "#3078BB",
        borderRadius: 20,
        padding: 35,
        alignItems: "center",
        shadowColor: "#000",
        shadowOffset: {
            width: 0,
            height: 2
        },
        shadowOpacity: 0.25,
        shadowRadius: 3.84,
        elevation: 5
    },

    imgs1: {

        height: 100,
        width: 100
    },
    openButton: {
        backgroundColor: "#62AFDD",

        borderRadius: 5,
        padding: 10,
        elevation: 2,
        marginTop: 10,
        width: 100,
        fontSize: 8,
    },
    chooseButton: {
        backgroundColor: "#CC975D",
        borderColor: '#80B3D5',
        borderRadius: 5,
        padding: 10,
        elevation: 2,
        marginTop: 2,
        width: 120,
        fontSize: 8,
        marginBottom: 10,
    },
    fmButton: {
        backgroundColor: "#62AFDD",
        borderRadius: 5,
        padding: 10,
        elevation: 2,
        marginTop: 10,
        width: 120,
        fontSize: 8,
        marginLeft: 50

    },
    textStyle: {
        color: "white",
        fontWeight: "bold",
        textAlign: "center"
    },
    modalText: {
        marginBottom: 15,
        textAlign: "center",
        color: '#fff'
    },
    contaner: {
        flexDirection: 'row',
        justifyContent: 'space-around',
        height: 170

    },
    contanerleft: {
        width: 250,
        marginRight: 50,

        shadowColor: "black",
        textAlign: "center",



    },
    tikutitle: {
        textAlign: "center",
        marginTop: 50,

    },
    yikutype: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center",

    },
    contanerright: {
        width: 100,
        // backgroundColor: "red",
    },
    tinyLogo: {
        resizeMode: 'stretch',
        position: 'absolute',
        width: 150,
        height: 180


    },
    choosefengmian: {
        // width: 700,
        height: 300,
        marginLeft: 50,
        marginRight: 50,
        display: "flex",
        flexWrap: "wrap",
        // justifyContent: 'space-around',
        alignItems: "center",
        marginTop: 50


    },
    images: {
        width: 120,
        height: 140,
        marginTop: 10,
        borderColor: '#78FAF6',
        borderWidth: 2,
        shadowColor: "#78FAF6",
        display: 'flex',
        justifyContent: 'center',
        alignItems: "center"
        // shadowOffset: {
        //     width: 0,
        //     height: 0
        // },
        // shadowOpacity: 0.25,
        // shadowRadius: 3.84,
        // elevation: 5
        // flex:1
    },
    a1: {
        width: 118,
        height: 138
    },
    radios: {
        flexDirection: "row",//rn默认column
        color: "#fff",
        top: -10

    },
})
